﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Forecast.Logica.Enumeradores
Imports Forecast.Logica.Servicios
Imports Forecast.Logica.Modelos
Public Class MantenedorUsuario
    Inherits System.Web.UI.Page
    Private Shared CapIn As usuamanager

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            If Session("MasterP") <> "" And Session("SysRol") = 2 Then
                ' esto carga cuando entra el usuario que no es administrador para mostrar solo la informacion de usuarios
                ModificaUsuarios(Session("SysUsuario"))
                ImageButton1.Visible = False
                BtnCancelar.Visible = False
                LkBtnCrearNuevo.Visible = False
                ImageButton2.Visible = False
                LkBtnEditar.Visible = False

                LblActivo.Visible = False
                LblArriendo.Visible = False
                LblCargoFijo.Visible = False
                LblMantencion.Visible = False

                Txtmantencion.Visible = False
                TxtcargoFijo.Visible = False
                txtArriendo.Visible = False
                ChActivo.Visible = False

            End If
        End If
    End Sub
    Protected Sub LkBtnCrearNuevo_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        txtnombre.Text = ""
        TxtEmail.Text = ""
        TxtDireccion.Text = ""
        TxtFono.Text = ""
        TxtFonoMovil.Text = ""
        'Label1.Visible = False
        TxtRut.Text = ""
        TxtRut.Enabled = True
        ChActivo.Checked = True
        BtnCrearUser.Visible = True
        BtnCancelar.Visible = False
        BtnReanudar.Visible = False
        BtnGuardarIngreso.Visible = False
        Label3.Text = "CREAR CUENTAS DE USUARIOS"
        TbIngreso.Visible = True
        UpdatePanel2.Visible = False
    End Sub

    Protected Sub LkBtnEditar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Label9.Visible = False
        TbIngreso.Visible = False
        BtnCrearUser.Visible = False
        BtnCancelar.Visible = True
        BtnReanudar.Visible = True
        BtnGuardarIngreso.Visible = True
        UpdatePanel2.Visible = True
    End Sub

    Protected Sub BtnCancelar_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        TbIngreso.Visible = False
        UpdatePanel2.Visible = True
    End Sub

    Protected Sub btn_buscar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        cargarBusqueda()
    End Sub

    Private Sub cargarBusqueda()
        Dim condi1, condi2, condi3, condi4, condi5, condi6, condi7 As String

        'condi1 = " and dbo.TB_Clientes.Nombre LIKE '%" & txt_Busqueda.Text & "%' "
        'condi2 = " or dbo.TB_Clientes.ApellidoPaterno LIKE '%" & txt_Busqueda.Text & "%'"
        'condi3 = " or dbo.TB_Clientes.ApellidoMaterno LIKE '%" & txt_Busqueda.Text & "%'"
        'condi4 = " or dbo.TB_Clientes.Rut LIKE '%" & txt_Busqueda.Text & "%'"
        'condi6 = " or dbo.TB_Clientes.Medidor like '%" & txt_Busqueda.Text & "%'"
        'condi7 = " or dbo.TB_Clientes.Parcela like '%" & txt_Busqueda.Text & "%'"

        'If Session("SysRol") <> 1 Then
        '    condi5 = "and  TB_Clientes.Sysid = " & Session("SysUsuario") & " "
        'End If



        Dim Dtab3 As Data.DataTable
        Dim objDRP As System.Data.DataRow
        Dim EDE, i As Integer
        Dim objDTP As System.Data.DataTable
        Dim UserSis, Passw, Vall As String
        objDTP = New System.Data.DataTable("Etapa")
        objDTP.Columns.Add("IdUsuario", GetType(Integer))
        objDTP.Columns.Add("IdRole", GetType(Integer))
        objDTP.Columns.Add("DesRole", GetType(String))
        objDTP.Columns.Add("Username", GetType(String))
        objDTP.Columns.Add("Password", GetType(String))
        objDTP.Columns.Add("Name", GetType(String))
        objDTP.Columns.Add("IdEntityF", GetType(Integer))
        objDTP.Columns.Add("DesEntity", GetType(String))

        CapIn = New usuamanager

        Dtab3 = CapIn.ap_DescripcionesUsuarios(condi1, condi2, condi3, condi4, condi6, condi7)
        EDE = Dtab3.Rows.Count
        If Dtab3.Rows.Count > 0 Then
            For i = 0 To EDE - 1 Step 1
                objDRP = objDTP.NewRow
                objDRP("IdUsuario") = Dtab3.Rows(i).Item("IdUsuario").ToString
                objDRP("IdRole") = Dtab3.Rows(i).Item("IdRole").ToString
                objDRP("DesRole") = Dtab3.Rows(i).Item("DesRole").ToString
                objDRP("Username") = Dtab3.Rows(i).Item("Username").ToString
                objDRP("Password") = Dtab3.Rows(i).Item("Password").ToString
                objDRP("Name") = Dtab3.Rows(i).Item("Name")
                objDRP("IdEntityF") = Dtab3.Rows(i).Item("IdEntityF").ToString
                objDRP("DesEntity") = Dtab3.Rows(i).Item("DesEntity").ToString

                'Passw = Dtab3.Rows(i).Item("Pass").ToString
                'If Passw <> "" Then
                '    UserSis = Trim(Dtab3.Rows(i).Item("Rut").ToString) & "AguasProfundas2014"
                '    Vall = CapIn.Decrypt(Passw, UserSis)
                '    objDRP("PassWW") = Vall
                'Else
                '    objDRP("PassWW") = ""
                'End If

                objDTP.Rows.Add(objDRP)
            Next
        End If

        Session("grUsuario") = objDTP
        GridView1.DataSource = objDTP
        GridView1.DataBind()
        TbResultadoBusqueda.Visible = True
    End Sub
    Protected Sub BtnCrearUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnCrearUser.Click
        Dim Dtab3 As Data.DataTable

        If Trim(txtnombre.Text) = "" Then
            Exit Sub
        End If

        Dim Passw, UserSis, Vall, NombreReal, Email, IDCargo, PassFinal, PassAleatoria As String
        Dim GerenteCargo As Integer
        Dim r1 As New Random()
        Dim r2 As New Random()
        Dim Alea1, Alea2 As Integer
        Dim subject, fromcorreo, CodFonoFijo As String
        Dim mensaje, EmailAbog, NomAbog, Fono, FonoModo As String
        Dim servidor As String
        Dim direcc As String
        Dim miFecha As DateTime = DateTime.Now()
        Dim fechaS, LoginUserExit As String
        fechaS = String.Format("{0:dd/MM/yyyy}", miFecha)

        NombreReal = txtnombre.Text
        Email = TxtEmail.Text
        CapIn = New usuamanager


        PassAleatoria = "aguas"
        PassFinal = "AguasProfundas2013"  'PassAleatoria & "" & Alea1

        Vall = CapIn.Encrypt(PassAleatoria, PassFinal)
        CapIn.CrearUser(Trim(txtnombre.Text), Trim(txtApellido.Text), Trim(TxtRut.Text), Trim(TxtEmail.Text), Trim(TxtFono.Text), Trim(TxtFonoMovil.Text), "", Trim(TxtDireccion.Text), Trim(txtParcela.Text), Trim(txtMedidor.Text), Trim(Txtmantencion.Text), Trim(TxtcargoFijo.Text), Trim(txtArriendo.Text), Vall, ChActivo.Checked)

        Label4.Text = " Se ha Creado una cuenta para Usuario " & Trim(txtnombre.Text) '& ". La Clave de Acceso fue enviada por Correo Electrónico a la cuenta indicada."
        Label4.Visible = True
        'CapIn = Nothing

        txtnombre.Text = ""
        TxtEmail.Text = ""
        TxtRut.Text = ""
        TxtDireccion.Text = ""
        TxtFono.Text = ""
        TxtFonoMovil.Text = ""

        TbIngreso.Visible = False
        UpdatePanel2.Visible = True

    End Sub

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.Pager Then
            Dim _TotalPags As Label = e.Row.FindControl("lblTotalNumberOfPages")
            _TotalPags.Text = GridView1.PageCount.ToString
            Dim _IraPag As TextBox = e.Row.FindControl("IraPag")
            _IraPag.Text = (Me.GridView1.PageIndex + 1).ToString

            Dim _DropDownList As DropDownList = e.Row.FindControl("RegsPag")
            _DropDownList.SelectedValue = Me.GridView1.PageSize.ToString
        ElseIf e.Row.RowType = DataControlRowType.DataRow Then

            e.Row.Attributes.Add("OnMouseOut", "this.className = this.orignalclassName;")
            e.Row.Attributes.Add("OnMouseOver", "this.orignalclassName = this.className;this.className = 'altoverow';")
        End If
    End Sub

    Protected Sub BtnGuardarIngreso_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnGuardarIngreso.Click
        Try
            If Session("entrada") = 1 Then


                Label3.Text = "CREAR CUENTAS DE USUARIOS"
                Dim Passw, UserSis, Vall, NombreReal, Email, IDCargo As String
                Dim CodFonoFijo, Fono, FonoModo As String
                Dim GerenteCargo As Integer

                NombreReal = txtnombre.Text
                Email = TxtEmail.Text

                Fono = TxtFono.Text
                FonoModo = TxtFonoMovil.Text

                UserSis = Trim(TxtRut.Text) & "American09"
                CapIn = New usuamanager
                Vall = CapIn.Encrypt(Passw, UserSis)
                CapIn.ModUser(Session("idUsuario"), Trim(txtnombre.Text), Trim(txtApellido.Text), Trim(TxtRut.Text), Trim(TxtEmail.Text), Trim(TxtFono.Text), Trim(TxtFonoMovil.Text), "", Trim(TxtDireccion.Text), Trim(txtParcela.Text), Trim(txtMedidor.Text), Trim(Txtmantencion.Text), Trim(TxtcargoFijo.Text), Trim(txtArriendo.Text), ChActivo.Checked)

                CapIn = Nothing

                Label4.Text = "Se ha modificado la cuenta de: " & txtnombre.Text
                Label4.Visible = True
                If Session("MasterP") <> "" And Session("SysRol") = 1 Then
                    cargarBusqueda()
                    TbIngreso.Visible = False
                    UpdatePanel2.Visible = True
                    TABLE2.Visible = True

                    txtnombre.Text = ""
                    TxtEmail.Text = ""
                    TxtRut.Text = ""
                    TxtDireccion.Text = ""
                    TxtFono.Text = ""
                    TxtFonoMovil.Text = ""
                    Session("entrada") = 0
                End If

            End If
        Catch ex As Exception


        End Try

    End Sub

    Protected Sub BtnReanudar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnReanudar.Click
        Dim Passw, UserSis, Vall, NombreReal, Email, IDCargo As String
        Dim CodFonoFijo, Fono, FonoModo, fechaS As String
        Dim miFecha As DateTime = DateTime.Now()
        fechaS = String.Format("{0:dd/MM/yyyy}", miFecha)

        NombreReal = txtnombre.Text
        Email = TxtEmail.Text
        Fono = TxtFono.Text
        FonoModo = TxtRut.Text

        Day(DateAdd("d", 1, fechaS))

        UserSis = Trim(TxtRut.Text) & "American09"
        CapIn = New usuamanager
        Vall = CapIn.Encrypt("info", UserSis)
        CapIn.FormatPass(Session("idUsuario"), Vall)
        Label4.Text = "Se ha Formateado la Clave, la nueva clave es:    info"
        Label4.Visible = True
        CapIn = Nothing
    End Sub

    Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
        txtnombre.Text = ""
        TxtEmail.Text = ""
        TxtDireccion.Text = ""
        TxtFono.Text = ""
        TxtFonoMovil.Text = ""
        txtApellido.Text = ""
        txtMedidor.Text = ""
        Txtmantencion.Text = ""
        txtParcela.Text = ""
        TxtcargoFijo.Text = ""
        txtArriendo.Text = ""

        'Label1.Visible = False
        TxtRut.Text = ""
        TxtRut.Enabled = True
        ChActivo.Checked = True
        BtnCrearUser.Visible = True
        BtnCancelar.Visible = False
        BtnReanudar.Visible = False
        BtnGuardarIngreso.Visible = False
        Label3.Text = "CREAR CUENTAS DE USUARIOS"
        TbIngreso.Visible = True
        UpdatePanel2.Visible = False
    End Sub

    Protected Sub ImageButton2_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton2.Click
        Label9.Visible = False
        TbIngreso.Visible = False
        BtnCrearUser.Visible = False
        BtnCancelar.Visible = True
        BtnReanudar.Visible = True
        BtnGuardarIngreso.Visible = True
        UpdatePanel2.Visible = True
    End Sub


    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
        Dim index As Integer = Convert.ToInt32(e.CommandArgument)
        Dim selectedRow As GridViewRow = GridView1.Rows(index)
        Dim sysid As Integer = GridView1.Rows.Item(index).Cells(0).Text  '.Item(index).Cells(0).Text ' selectedRow.Cells(0)


        ModificaUsuarios(sysid)
    End Sub
    Private Sub ModificaUsuarios(ByVal Sysid)
        Dim objDT, objDT2 As System.Data.DataTable
        Dim objDR As System.Data.DataRow
        Dim IDUSuario, EDE, i As Integer

        ' If e.CommandArgument = "4" Then
        CapIn = New usuamanager
        objDT = Session("grUsuario")
        objDT2 = CapIn.ap_DescripcionesUsuariosSelMod(Sysid)
        EDE = objDT2.Rows.Count
        If objDT2.Rows.Count > 0 Then
            txtnombre.Text = objDT2.Rows(0).Item("Nombre").ToString
            txtApellido.Text = objDT2.Rows(0).Item("ApellidoPaterno").ToString
            TxtRut.Text = objDT2.Rows(0).Item("Rut").ToString
            TxtDireccion.Text = objDT2.Rows(0).Item("Direccion").ToString

            txtParcela.Text = objDT2.Rows(0).Item("Parcela").ToString
            txtMedidor.Text = objDT2.Rows(0).Item("Medidor").ToString
            Txtmantencion.Text = objDT2.Rows(0).Item("Mantencion").ToString
            TxtcargoFijo.Text = objDT2.Rows(0).Item("CargoFijo").ToString
            txtArriendo.Text = objDT2.Rows(0).Item("Arriendo").ToString

            TxtEmail.Text = objDT2.Rows(0).Item("Email").ToString
            TxtFono.Text = objDT2.Rows(0).Item("TelefonoFijo").ToString
            TxtFonoMovil.Text = objDT2.Rows(0).Item("TelefonoMovil").ToString
            ChActivo.Checked = objDT2.Rows(0).Item("Activo").ToString

            Session("entrada") = 1

            Label4.Visible = False
            TxtRut.Enabled = False
            Session("idUsuario") = objDT2.Rows(0).Item("Sysid")
            BtnCrearUser.Visible = False
            Label3.Text = "MODIFICANDO CUENTAS DE USUARIOS"
            TbIngreso.Visible = True
            UpdatePanel2.Visible = False
        End If

        CapIn = Nothing

    End Sub


    Protected Sub btncambiarClave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btncambiarClave.Click
        Response.Redirect("Cambiopass.aspx", True)
    End Sub

End Class